import Validator from "./validator.js"
import ajax from "./ajax.js"
import { getCookie, setCookie } from "./cookie_utils.js"

if (getCookie('token') !== undefined) {
    // 已登录 直接返回首页
    window.location.href = './index.html'
}
if (getCookie("isRemberMe")) {
    const { name, password: pwd } = JSON.parse(getCookie("isRemberMe"))
    username.value = name;
    password.value = pwd
    isRemeber.checked = true

}

const validator = new Validator()

username.addEventListener("focus", e => callout.style.display = 'none')
password.addEventListener("focus", e => callout.style.display = 'none')



btn.addEventListener("click", async (e) => {
    e.preventDefault();

    validator.add(username.value, 'isNotEmpty', '用户名不能为空!')
    validator.add(password.value, 'isNotEmpty', '密码不能为空!')
    validator.add(password.value, 'minLength:6', '密码最小长度为6位!')

    let checkRes = validator.validator()

    callout.style.display = 'block'

    if (checkRes === 'success') {
        // 发送ajax请求
        try {
            const result = await ajax({
                method: "POST",
                url: '/api/login',
                data: `name=${username.value}&password=${password.value}`
            })

            const { data, code } = JSON.parse(result)

            callout.innerText = checkRes

            if (code === 200) {
                // 设置 登录cookie 过期时间 30s 

                const token = JSON.stringify(data)

                setCookie("token", token, 30)
                // 设置记住我 过期时间为1天
                !getCookie("isRemberMe")
                    ? (isRemeber.checked ? setCookie("isRemberMe", token, 3600 * 24) : "")
                    : (isRemeber.checked ? "" : setCookie("isRemberMe", null, -1))

                let timer = setTimeout(_ => {
                    clearTimeout(timer)
                    window.location.href = '/index.html'
                }, 1000)
            } else {
                callout.innerText = data
            }
        } catch (error) {
            console.log(error)
        }
        return
    }

    callout.innerText = checkRes

})
